package com.javafamily.controller;

import com.javafamily.bean.Pets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer/pets")
public class PetsController {
    //注入RestTemplate模板对象
    //RestTemplate  用来发送Http请求，HttpUrlConnection、HttpClient、OkHttp
    @Autowired
    private RestTemplate restTemplate;

    // 配置请求地址：硬编码，将配置信息写死在代码中
    // 怎么才能不硬，写在配置文件中、配置中心中
    private static final String SERVICE_PROVIDER = "http://localhost:8081";

    //跨服务新增
    @PostMapping("/save")
    public boolean saveHandle(@RequestBody Pets pets) {
        String url = SERVICE_PROVIDER + "/provider/pets/save";
        // TODO 问题：消费者直连提供者行不行？
        // 结论：不行
        Boolean result = restTemplate.postForObject(url, pets, Boolean.class);
        return result;
    }

    //跨服务根据id删除
    @DeleteMapping("/del/{id}")
    public void deleteHandle(@PathVariable("id") int id) {
        String url = SERVICE_PROVIDER + "/provider/pets/del/" + id;
        restTemplate.delete(url);
    }

    //跨服务修改
    @PutMapping("/update")
    public void updateHandle(@RequestBody Pets pets) {
        String url = SERVICE_PROVIDER + "/provider/pets/update";
        restTemplate.put(url, pets, Boolean.class);
    }

    //跨服务根据id查询
    @GetMapping("/get/{id}")
    public Pets getHandle(@PathVariable("id") int id) {
        String url = SERVICE_PROVIDER + "/provider/pets/get/" + id;
        Pets pets = restTemplate.getForObject(url, Pets.class);
        return pets;
    }

    //跨服务根据列表查询
    @GetMapping("/list")
    public List<Pets> listHandle() {
        String url = SERVICE_PROVIDER + "/provider/pets/list/";
        List list = restTemplate.getForObject(url, List.class);
        return list;
    }
}
